import { ref, onUnmounted } from 'vue'
import type { Ref } from 'vue'

export default function useWindowDrag(name?: string): {
  isKeyDown: Ref<boolean>
  isDragging: Ref<boolean>
  handleMouseDown: (event: MouseEvent) => void
} {
  const isKeyDown = ref(false)

  const isDragging = ref(false)
  const startX = ref(0)
  const startY = ref(0)
  const threshold = ref(5) // 拖动阈值

  let onMouseMove: (ev: MouseEvent) => void
  let onMouseUp: () => void

  const handleMouseDown = (event: MouseEvent): void => {
    // 如果不是鼠标左键，则不执行任何操作
    if (event.button !== 0) return
    window.electron.ipcRenderer.invoke('renderer-to-main', {
      name: `${name}-start-drag`
    })

    isKeyDown.value = true

    startX.value = event.clientX
    startY.value = event.clientY
    isDragging.value = false;


    onMouseMove = (ev: MouseEvent): void => {
      if (isKeyDown.value) {
        if (name) {
          window.electron.ipcRenderer.invoke('renderer-to-main', {
            name: `${name}-move-drag`
          })
        }

        const dx = ev.clientX - startX.value
        const dy = ev.clientY - startY.value
        if (Math.sqrt(dx * dx + dy * dy) > threshold.value) {
          isDragging.value = true
        }
      }
    }
    document.addEventListener('mousemove', onMouseMove)

    onMouseUp = (): void => {
      window.electron.ipcRenderer.invoke('renderer-to-main', { name: `${name}-stop-drag` })

      isKeyDown.value = false
      document.removeEventListener('mousemove', onMouseMove as EventListener)
      document.removeEventListener('mouseup', onMouseUp as EventListener)
    }

    document.addEventListener('mousemove', onMouseMove as EventListener)
    document.addEventListener('mouseup', onMouseUp)

  }
  // 清理事件监听器
  onUnmounted(() => {
    if (onMouseMove) document.removeEventListener('mousemove', onMouseMove as EventListener)
    if (onMouseUp) document.removeEventListener('mouseup', onMouseUp as EventListener)
  })

  return {
    isKeyDown,
    isDragging,
    handleMouseDown
  }
}
